from enum import Enum

from django.http import HttpResponse
from django.http import JsonResponse
from django.http import *
from django.views import View
import json
import datetime
from django.utils import timezone


from apps.orders.models import Order
from apps.houses.models import House
from apps.houses.models import HouseImage
from apps.users.models import User
from utils.relogin import LoginRequiredJSONMixin
from rest_framework.viewsets import ModelViewSet

class OrderAddView(LoginRequiredJSONMixin,View):
    def post(self,request):
        user = request.user
        user_id = user.id
        # 1. 接收参数
        data = json.loads(request.body.decode())
        # 2. 提取参数
        house_id = data.get('house_id')
        # user_id = data.get('user_id')
        begin_date = data.get('start_date')
        end_date = data.get('end_date')
        # 3. 验证参数
        if not all([house_id,begin_date,end_date]):
            return JsonResponse({'code':400,'errmsg':'缺少必传参数'})

        house = House.objects.get(id = house_id)

        # 判断订购房间
        new_time = datetime.date.today()
        if house.room_count > 0:
            order = Order.objects.filter(house_id=house_id,end_date=new_time,user_id=user_id)
            print(order)
            if order:
                return JsonResponse({'code':0,'errmsg':'您已经预定该房间'})
        else:
            return JsonResponse({'code':0,'errmsg':'没有房间了'})

        # 4. 数据入库
        begin_date = datetime.datetime.strptime(begin_date, '%Y-%m-%d')
        end_date = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        days = (end_date - begin_date).days
        print(type(days))

        if days == 0:
            days = 1

        elif days < house.min_days:
            return JsonResponse({'code':0,'errmsg':'该房间最少入住%s天'%house.min_days})

        orders = Order.objects.create(
            user_id = user_id,
            house_id = house_id,
            begin_date = begin_date,
            end_date = end_date,
            days = days,
            house_price=0,
            amount=0,
            status=Order.ORDER_STATUS['WAIT_ACCEPT']
        )

        orders.house_price = orders.house_price
        orders.amount = orders.house_price * days + house.deposit
        house.room_count -= 1
        house.order_count += 1

        orders.save()
        house.save()

        # 5. 返回响应
        return JsonResponse({'errno':0, 'errmsg':'下单成功'})

from apps.users.views import QNYUN_URL
class OrderInfoView(LoginRequiredJSONMixin,View):

    # order_id = ['order_id']

    def get(self,request):
        # 必须是登录用户
        user = request.user

        roles = request.GET
        role = roles['role']

        domain_name = QNYUN_URL
        data_list = []
        if role == 'landlord':
            houses = House.objects.filter(user_id=user.id)
            for house in houses:
                houses_id = house.id
                data_info = Order.objects.filter(house_id=houses_id)
                for data in data_info:
                    status = Order.ORDER_STATUS_ENUM[data.status]
                    data_list.append({
                        "order_id": data.id,
                        "begin_date": data.begin_date,
                        "end_date": data.end_date,
                        "days": data.days,
                        "amount": data.amount,
                        "status": status,
                        "comment": data.comment,
                        "ctime": data.create_time,
                        "img_url": domain_name + data.house.index_image_url,
                        "title": data.house.title
                    })
            # 返回响应
            return JsonResponse({'data': {'orders': data_list}, 'errmsg': 'ok', 'errno': 0})


        elif role == 'custom':
            data = Order.objects.filter(user_id=user.id).order_by('-create_time')
            data_list = []
            for data_l in data:
                status = Order.ORDER_STATUS_ENUM[data_l.status]
                data_list.append({
                    "order_id": data_l.id,
                    "begin_date": data_l.begin_date,
                    "end_date": data_l.end_date,
                    "days": data_l.days,
                    "amount": data_l.amount,
                    "status": status,
                    "comment": data_l.comment,
                    "ctime": data_l.create_time,
                    "img_url": domain_name + data_l.house.index_image_url,
                    "title": data_l.house.title
                })

            # 返回响应
            return JsonResponse({'data': {'orders': data_list}, 'errmsg': 'ok', 'errno': 0})


class OrderAcceptRejectView(View):
    def put(self,request,order_id):
        # 接收参数
        data = json.loads(request.body.decode())
        #  提取参数
        action = data.get('action')
        reason = data.get('reason')
        #  验证参数
        # if data.status != 0:
        #     return JsonResponse({'errno':0,'errmsg':'必须是新订单'})
        try:
            orders = Order.objects.filter(status='0')
        except Order.DoesNotExist:
            return JsonResponse({'errno':400,'errmsg':'必须是新订单'})

        if action == 'accept':
            Order.objects.filter(id=order_id).update(status='3')
        elif action == 'reject':
            Order.objects.filter(id=order_id).update(status='6')
            Order.objects.filter(id=order_id).update(comment=reason)
        # 返回响应
        return JsonResponse({'errno':0,'errmsg':'操作成功'})

class OrderCommentView(View):
    def put(self,request,order_id):
        data = json.loads(request.body.decode())
        comment = data.get('comment')
        Order.objects.filter(id=order_id).update(comment=comment)
        return JsonResponse({'errno':0,'errmsg':'评论成功'})